#!/bin/bash

################################################################################
#    Copyright (c) 2017, 2022 Red Hat Inc
#
#    This program and the accompanying materials are made
#    available under the terms of the Eclipse Public License 2.0
#    which is available at https://www.eclipse.org/legal/epl-2.0/
#
#    SPDX-License-Identifier: EPL-2.0
#
#    Contributors:
#        Red Hat Inc - initial API and implementation
################################################################################

JETTY_HOME="/opt/jetty"
JETTY_BASE="/var/opt/jetty"

START_ARGS="$START_ARGS -Djetty.home=${JETTY_HOME}"
START_ARGS="$START_ARGS -Djetty.base=${JETTY_BASE}"

# START_ARGS : Arguments to the starter JVM
# JAVA_OPTS : Arguments to the server JVMs

# Certificate Options

: ${KAPUA_SSL_ENABLE:="false"}

if [ "${KAPUA_SSL_ENABLE}" == "true" ]; then
    # Keystore configuration
    CERTIFICATES_PATH="tls"
    if [ ! -d "${JETTY_BASE}/${CERTIFICATES_PATH}" ]; then
        mkdir -p "${JETTY_BASE}/${CERTIFICATES_PATH}"
    fi
    : ${KEYSTORE_NAME:="kapua.pkcs12"}
    : ${KAPUA_KEYSTORE_PASSWORD:="changeit"}
    if [ ! -f "${JETTY_BASE}/${CERTIFICATES_PATH}/${KEYSTORE_NAME}" ]; then
        if [ -z "${KAPUA_KEYSTORE}" ]; then
            if [ -n "${KAPUA_KEY_PASSWORD}" ]; then
                PASSWORD_PARAM="-passin pass:${KAPUA_KEY_PASSWORD}";
            fi
            openssl pkcs12 -export -in <(echo "${KAPUA_CRT}"; echo "${KAPUA_CA}") -inkey <(echo "${KAPUA_KEY}") ${PASSWORD_PARAM} -name kapua -password pass:"${KAPUA_KEYSTORE_PASSWORD}" -out "${JETTY_BASE}/${CERTIFICATES_PATH}/${KEYSTORE_NAME}"
        else
            echo "${KAPUA_KEYSTORE}" | base64 --decode > "${JETTY_BASE}/${CERTIFICATES_PATH}/${KEYSTORE_NAME}"
        fi
    fi

    echo "jetty.sslContext.keyStorePath=${CERTIFICATES_PATH}/${KEYSTORE_NAME}" >> ${JETTY_BASE}/start.d/ssl.ini
    echo "jetty.sslContext.keyStorePassword=${KAPUA_KEYSTORE_PASSWORD}" >> ${JETTY_BASE}/start.d/ssl.ini
    echo "jetty.sslContext.trustStorePath=${CERTIFICATES_PATH}/${KEYSTORE_NAME}" >> ${JETTY_BASE}/start.d/ssl.ini
    echo "jetty.sslContext.trustStorePassword=${KAPUA_KEYSTORE_PASSWORD}" >> ${JETTY_BASE}/start.d/ssl.ini
    echo "jetty.sslContext.keyManagerPassword=${KAPUA_KEYSTORE_PASSWORD}" >> ${JETTY_BASE}/start.d/ssl.ini

else
    rm -f ${JETTY_BASE}/start.d/https.ini
    rm -f ${JETTY_BASE}/start.d/ssl.ini
fi

# Start Jetty

eval echo "START_ARGS = $START_ARGS"
eval echo "JAVA_OPTS = $JAVA_OPTS"
eval exec /usr/bin/java --add-opens java.base/java.lang=ALL-UNNAMED $START_ARGS -jar /opt/jetty/start.jar $JAVA_OPTS "$@"
